package com.lanchetech.user.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaSecCheckService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaAnalysisServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaSecCheckServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.bean.analysis.WxMaSummaryTrend;
import cn.binarywang.wx.miniapp.bean.analysis.WxMaVisitTrend;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.collect.Lists;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.common.enums.ActivityEnum;
import com.lanchetech.dao.UserMapper;
import com.lanchetech.entity.FlashSaleActivity;
import com.lanchetech.entity.FlashSaleSpu;
import com.lanchetech.entity.User;
import com.lanchetech.service.FileService;
import com.lanchetech.service.InviteCodeService;
import com.lanchetech.user.service.MiniappService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class MiniappServiceImpl implements MiniappService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${wx.miniapp.configs.appid}")
    private String appid;

    @Value("${wx.miniapp.configs.secret}")
    private String secret;

    @Value("${wx.miniapp.configs.token}")
    private String token;

    @Value("${wx.miniapp.configs.aesKey}")
    private String aesKey;

    @Value("${wx.miniapp.configs.msgDataFormat}")
    private String msgDataFormat;

    @Value("${customer.hashid.salt}")
    private String salt;

    @Value("${domain.url}")
    private String domainUrl;

    @Autowired
    UserMapper userDAO;

    @Autowired
    InviteCodeService inviteCodeService;

    @Autowired
    FileService fileService;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<WxMaSummaryTrend> getSummaryTrend() {
        final WxMaService wxService = getMaService();
        WxMaAnalysisServiceImpl analysis = new WxMaAnalysisServiceImpl(wxService);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        Date oneDayBefore = calendar.getTime();

        try {
            List<WxMaSummaryTrend> list = analysis.getDailySummaryTrend(oneDayBefore, oneDayBefore);
            return list;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<WxMaVisitTrend> getMonthlySummaryTrend() {
        final WxMaService wxService = getMaService();
        WxMaAnalysisServiceImpl analysis = new WxMaAnalysisServiceImpl(wxService);
        Calendar cale = null;
        // 获取当月第一天和最后一天
        Date firstday, lastday;
        // 获取前月的第一天
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, -1);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        firstday = cale.getTime();
        // 获取前月的最后一天
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        lastday = cale.getTime();

        try {
            List<WxMaVisitTrend> list = analysis.getMonthlyVisitTrend(firstday, lastday);
            return list;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<WxMaVisitTrend> getWeeklySummaryTrend() {
        final WxMaService wxService = getMaService();
        WxMaAnalysisServiceImpl analysis = new WxMaAnalysisServiceImpl(wxService);
        Calendar cale = null;
        Date firstday, lastday;
        cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_WEEK, 2);
        cale.add(Calendar.DATE, -7);
        firstday = cale.getTime();
        cale.add(Calendar.DATE, 6);
        lastday = cale.getTime();

        try {
            List<WxMaVisitTrend> list = analysis.getWeeklyVisitTrend(firstday, lastday);
            return list;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public WxMaSecCheckService wxMaSecCheckService() {
        WxMaSecCheckService wxMaSecCheckService = new WxMaSecCheckServiceImpl(getMaService());
        return wxMaSecCheckService;
    }

    @Override
    public String getUserOpenid(String code) {
        final WxMaService wxService = getMaService();
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            return session.getOpenid();
        } catch (WxErrorException e) {
            log.error(e.toString());
            return null;
        }
    }

    @Override
    public WxMaJscode2SessionResult getUserSession(String code) {
        final WxMaService wxService = getMaService();
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            return session;
        } catch (WxErrorException e) {
            log.error(e.toString());
            return null;
        }
    }

    private WxMaService getMaService() {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(this.appid);
        config.setSecret(this.secret);
        config.setToken(this.token);
        config.setAesKey(this.aesKey);
        config.setMsgDataFormat(this.msgDataFormat);
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        return service;
    }

    @Override
    public WxMaPhoneNumberInfo getUserPhone(String sessionKey, String encryptedData, String ivStr) {
        final WxMaService wxService = getMaService();
        return wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, ivStr);
    }

    @Override
    public WxMaUserInfo getUserInfo(String sessionKey, String encryptedData, String ivStr) {
        final WxMaService wxService = getMaService();
        return wxService.getUserService().getUserInfo(sessionKey, encryptedData, ivStr);
    }

    @Override
    public ResultData<WxMaLiveResult> getLiveInfo(Integer pageNo, Integer pageSize) {
        final WxMaService wxService = getMaService();
        try {
            return new ResultData<>(wxService.getLiveService().getLiveInfo(pageNo, pageSize));
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return new ResultData<>();
    }

    @Override
    public ResultData<String> createMiniLiveQrcode(User user) {
        String shareUrl = domainUrl + "/liveShare";
        if (user != null) {
            shareUrl = shareUrl + "&inviteCode=" + inviteCodeService.generateInviteCode(user.getId());
        }
        try {
            String qrcode = fileService.createQrcodeBase64(shareUrl, 100, 100);
            return new ResultData<>(qrcode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultData<>(null);
    }

}